﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ProjectsController.cs" company="DissingNellemann">
//   
// All rights reserved </copyright>
// <summary>
//   The projects controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Website.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using Website.CRUDServices;
    using Website.Models;
    using Website.Models.Styling;
    using Website.Models.ViewModels;

    using Project = Website.Models.ViewModels.Project;

    /// <summary>
    ///     The projects controller.
    /// </summary>
    public class ProjectsController : BaseController
    {
        #region Public Methods and Operators

        /// <summary>
        ///     The get header items.
        /// </summary>
        /// <returns>
        ///     The list of headeritems for a newsinformation view.
        /// </returns>
        public static List<TableViewHeaderItem> GetHeaderItems()
        {
            var headerItems = new List<TableViewHeaderItem>();
            var item1 = new TableViewHeaderItem { Text = "Dato", SortableName = "Date", IsSortable = true, };

            var item2 = new TableViewHeaderItem { Text = "Lokation", SortableName = "Location.Name", IsSortable = true };
            var item3 = new TableViewHeaderItem { Text = "Navn", SortableName = "Name", IsSortable = true };
            var item4 = new TableViewHeaderItem
                            {
                                Text = "Beskrivelse",
                                SortableName = string.Empty,
                                IsSortable = false
                            };
            var item5 = new TableViewHeaderItem
                            {
                                Text = "Projekt type",
                                SortableName = "Status.Type",
                                IsSortable = true
                            };
            var item6 = new TableViewHeaderItem
                            {
                                Text = "Patent",
                                SortableName = "Status.PatentName",
                                IsSortable = true
                            };
            headerItems.Add(item1);
            headerItems.Add(item2);
            headerItems.Add(item3);
            headerItems.Add(item4);
            headerItems.Add(item5);
            headerItems.Add(item6);

            return headerItems;
        }

        /// <summary>
        /// The index.
        /// </summary>
        /// <param name="skip">
        /// The skip.
        /// </param>
        /// <param name="take">
        /// The take.
        /// </param>
        /// <param name="orderBy">
        /// The order by.
        /// </param>
        /// <param name="sortAscending">
        /// The sort ascending.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index(int? skip, int? take, string orderBy, bool? sortAscending)
        {
            this.Session["CurrentSubMenuSelection"] = "Projects";

            ListView<ProjectMeeting> view = null;

            List<TableViewHeaderItem> headerItems = GetHeaderItems();

            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new ProjectMeetingQuery
                                    {
                                        WithStatus = ProjectMeetingStatusType.None,
                                        Settings =
                                            new SearchSettings
                                                {
                                                    SortAscending = sortAscending ?? false,
                                                    Skip = skip ?? 0,
                                                    Take = take ?? 20,
                                                    OrderBy = !string.IsNullOrEmpty(orderBy) ? orderBy : "Date"
                                                }
                                    };

                    ProjectMeetingResult res = client.Query(query) as ProjectMeetingResult;
                    if (res != null)
                    {
                        view = new ListView<ProjectMeeting>(
                            res.List.ToList(),
                            skip ?? 0,
                            take ?? 20,
                            res.TotalRowCount,
                            query.Settings.OrderBy,
                            sortAscending ?? false,
                            headerItems,
                            "Index");

                        this.ViewData["ProjectTypes"] = PrimitiveTypes.GetProjectTypes();

                        this.ViewData["Locations"] = PrimitiveTypes.GetLocations();
                    }
                });

            return View(view);
        }

        /// <summary>
        ///     The new project.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult NewProject()
        {
            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Presentations"] = PrimitiveTypes.GetPresentations();
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["Demonstrations"] = PrimitiveTypes.GetDemonstrations();
            this.ViewData["Funds"] = PrimitiveTypes.GetFunds();
            this.ViewData["Groups"] = PrimitiveTypes.GetGroups();
            this.ViewData["Types"] = PrimitiveTypes.GetProjectTypes();
            this.ViewData["Roles"] = PrimitiveTypes.GetRoles();

            // grab profiles
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;
            return View();
        }

        /// <summary>
        /// The new project.
        /// </summary>
        /// <param name="projView">
        /// The the project.
        /// </param>
        /// <param name="statusType">
        /// The status type.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        [HttpPost]
        public ActionResult NewProject(Project projView, string statusType)
        {
            var projm = new ProjectMeeting
                            {
                                ID = Guid.NewGuid(),
                                OwnerID = projView.TheProject,
                                OwnerProjects = (projView.OwnerProjects ?? new List<Guid>()).ToArray(),
                                Name = projView.Name,
                                Date = (projView.Date!=null &&projView.Date>new DateTime(2000,1,1) ? projView.Date : null),
                                IsNational = projView.IsNational == "National",
                                LocationID = projView.Location,
                                Participants = (projView.Participants ?? new List<Guid>()).ToArray(),
                                Status = new ProjectMeetingStatus { ID = Guid.NewGuid() },
                                Groups = (projView.Groups ?? new List<Guid>()).ToArray()
                            };

            // build the base meeting from input
            projm.Status.PatentName = projView.StatusPatents.PatentName;

            // add information to the selected special case of the projectmeeting status
            switch (statusType)
            {
                case "SwitchStatusNotStarted":
                    projm.Status.StatusType = ProjectMeetingStatusType.NotStarted;
                    projm.Status.DemonstrationIDs = projView.StatusNotStarted.InnovationAndIdeas.ToArray();
                    projm.Status.GuidanceAbout = projView.StatusNotStarted.FundsGuidance.ToArray();
                    projm.Status.Financing = projView.StatusNotStarted.FundsApplication == null
                                                 ? new Guid[0]
                                                 : projView.StatusNotStarted.FundsApplication.ToArray();
                    projm.Status.GuidanceAboutText = projView.StatusNotStarted.GuidanceText;
                    projm.Status.FinancingText = projView.StatusNotStarted.ApplicationText;

                    break;

                case "SwitchStatusStarted":
                    projm.Status.StatusType = ProjectMeetingStatusType.Started;
                    projm.Status.Roles = projView.StatusStarted.Roles.ToArray();
                    projm.Status.Financing = projView.StatusStarted.Financing.ToArray();
                    projm.Status.FinancingText = projView.StatusStarted.FinancingComments;

                    break;

                case "SwitchStatusCompleted":
                    projm.Status.StatusType = ProjectMeetingStatusType.Completed;
                    projm.Status.DemonstrationIDs = projView.StatusCompleted.Demonstration.ToArray();

                    break;
            }

            projm.Status.Type = projView.StatusNotRAndD.Type != Guid.Empty
                                    ? projView.StatusNotRAndD.Type
                                    : projView.StatusRAndD.Type;
            projm.Status.Description = projView.StatusRAndD.MoreInformation
                                       + projView.StatusNotRAndD.MoreInformation;

            // save the projectmeeting
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var cmd = new CreateProjectMeetingCommand { ProjectMeeting = projm };
                    client.ExecuteCommand(cmd);
                });

            return this.RedirectToAction("Index");
        }

        public ActionResult UpdateProject(Guid id)
        {
            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Presentations"] = PrimitiveTypes.GetPresentations();
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["Demonstrations"] = PrimitiveTypes.GetDemonstrations();
            this.ViewData["Funds"] = PrimitiveTypes.GetFunds();
            this.ViewData["Groups"] = PrimitiveTypes.GetGroups();
            this.ViewData["Types"] = PrimitiveTypes.GetProjectTypes();
            this.ViewData["Roles"] = PrimitiveTypes.GetRoles();

            // grab profiles
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;

            // load object for editing
            var mm = new ProjectMeeting();
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    //get the Matchmaking object
                    var query = new ProjectMeetingQuery { Settings = new SearchSettings { IDEquals = id } };
                    var res = client.Query(query) as ProjectMeetingResult;
                    if (res != null)
                    {
                        if (res.List.Any())
                        {
                            mm = res.List[0];
                        }
                    }
                });
            // ensure we have some content
            if (mm != null)
            {
                return View(mm);
            }
            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult UpdateProject(Guid id, Guid statusId, Project projView, string statusType)
        {
            var projm = new ProjectMeeting
            {
                ID = id,
                OwnerID = projView.TheProject,
                OwnerProjects = (projView.OwnerProjects ?? new List<Guid>()).ToArray(),
                Name = projView.Name,
                Date = projView.Date,
                IsNational = projView.IsNational == "National",
                LocationID = projView.Location,
                Participants = (projView.Participants ?? new List<Guid>()).ToArray(),
                Status = new ProjectMeetingStatus { ID = statusId },
                Groups = (projView.Groups ?? new List<Guid>()).ToArray()
            };

            // build the base meeting from input
            projm.Status.PatentName = projView.StatusPatents.PatentName;

            // add information to the selected special case of the projectmeeting status
            switch (statusType)
            {
                case "SwitchStatusNotStarted":
                    projm.Status.StatusType = ProjectMeetingStatusType.NotStarted;
                    projm.Status.DemonstrationIDs = (projView.StatusNotStarted.InnovationAndIdeas ?? new List<Guid>()).ToArray();
                    projm.Status.GuidanceAbout = (projView.StatusNotStarted.FundsGuidance ?? new List<Guid>()).ToArray();
                    projm.Status.Financing = projView.StatusNotStarted.FundsApplication == null
                                                 ? new Guid[0]
                                                 : (projView.StatusNotStarted.FundsApplication ?? new List<Guid>()).ToArray();
                    projm.Status.GuidanceAboutText = projView.StatusNotStarted.GuidanceText;
                    projm.Status.FinancingText = projView.StatusNotStarted.ApplicationText;

                    break;

                case "SwitchStatusStarted":
                    projm.Status.StatusType = ProjectMeetingStatusType.Started;
                    projm.Status.Roles = (projView.StatusStarted.Roles ?? new List<Guid>()).ToArray();
                    projm.Status.Financing = (projView.StatusStarted.Financing ?? new List<Guid>()).ToArray();
                    projm.Status.FinancingText = projView.StatusStarted.FinancingComments;

                    break;

                case "SwitchStatusCompleted":
                    projm.Status.StatusType = ProjectMeetingStatusType.Completed;
                    projm.Status.DemonstrationIDs = (projView.StatusCompleted.Demonstration ?? new List<Guid>()).ToArray();

                    break;
            }

            projm.Status.Type = projView.StatusNotRAndD.Type != Guid.Empty
                                    ? projView.StatusNotRAndD.Type
                                    : projView.StatusRAndD.Type;
            projm.Status.Description = projView.StatusRAndD.MoreInformation
                                       + projView.StatusNotRAndD.MoreInformation;

            // save the projectmeeting
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var cmd = new UpdateProjectMeetingCommand { Dto = projm };
                    client.ExecuteCommand(cmd);
                });

            return this.RedirectToAction("Index");
        }
        #endregion
    }
}